<?php

class Core_Model_Table_Form extends Model_Table
{
	protected $_name = 'core_forms';

	/**
	 * get all types as options.
	 * @return array
	 */
	public function getTypesAsOptions()
	{
		$table = Agis::getTable('core@form.type');
		$ret = array();
		foreach ($table->fetchAll($table->select()->order('title')) as $row)
		{
			$ret[$row -> type] = $row -> title;
		}
		return $ret;
	}

	public function getFormsAsOptions()
	{
		$ret = array();
		foreach ($this->fetchAll() as $row)
		{
			$ret[$row -> form_id] = $row -> title;
		}
		return $ret;
	}

	public function getFormSpec($name)
	{
		$form = $this -> fetchRow($this -> select() -> where('name=?', $name));

		$table = Agis::getTable('core@form.element');

		$select = $table -> select() -> where('form_id=?', $form -> form_id) -> where('enabled=1') -> order('priority');

		$elements = $table -> fetchAll($select);

		return array(
				$form -> toArray(),
				$this -> prepareElements($elements -> toArray())
		);
	}

	public function prepareElements($elements)
	{
		$maps = array();

		/**
		 * elements
		 */
		foreach ($elements as $ele)
		{
			$maps[$ele['id']] = $this -> prepareElement($ele);
		}

		unset($elements);

		foreach ($maps as $index => $ele)
		{
			if (0 != ($pid = $ele['pid']))
			{
				if (isset($maps[$pid]))
				{
					if (isset($maps[$pid]))
					{
						$maps[$pid]['options']['children'][] = $ele;
					}
				}
				unset($maps[$index]);
			}

		}

		return $maps;
	}

	public function prepareElement($ele)
	{
		return array(
				'pid' => $ele['pid'],
				'type' => $ele['type'],
				'name' => $ele['name'],
				'options' => $ele['spec'] ? unserialize($ele['spec']) : array(),
		);
	}

	public function getForm($name)
	{
		$form = new Form_Design;
		$form -> setCode($name) -> prepare();
		return $form;
	}

}
